package com.yh.manage.course.service;

import com.lxw.framework.domain.course.CourseBase;
import com.lxw.framework.domain.course.Teachplan;
import com.lxw.framework.domain.course.ext.TeachplanNode;
import com.lxw.framework.exception.CastException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.ResponseResult;
import com.yh.manage.course.dao.CourseBaseRepository;
import com.yh.manage.course.dao.TeachplanMapper;
import com.yh.manage.course.dao.TeachplanRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class TeachplanService {

    @Resource
    private TeachplanMapper teachplanMapper;

    @Resource
    private TeachplanRepository teachplanRepository;

    @Resource
    private CourseBaseRepository courseBaseRepository;

    public TeachplanNode findTeachplanList(String courseId){
        return teachplanMapper.selectList(courseId);
    }

    /*
    * 添加课程计划信息
    * */
    public ResponseResult addTeachplan(Teachplan teachplan) {
        if (teachplan == null
                || StringUtils.isEmpty(teachplan.getCourseid())
                || StringUtils.isEmpty(teachplan.getPname())) {
            CastException.cast(CommonCode.VALIDATA);
        }
        Optional<CourseBase> courseBaseOptional = courseBaseRepository
                .findById(teachplan.getCourseid());
        if (!courseBaseOptional.isPresent()) {
            CastException.cast(CommonCode.VALIDATA);
        }
        CourseBase courseBase = courseBaseOptional.get();
        if (StringUtils.isEmpty(teachplan.getParentid())) {//添加的是二级节点
            List<Teachplan> teachplanList  = teachplanRepository
                    .findByCourseidAndParentid(teachplan.getCourseid(), "0");
           Teachplan root = new Teachplan();
            if ((teachplanList == null ||teachplanList.size()<=0)) {//根节点不存在，添加根节点
                String name = courseBase.getName();

                root.setParentid("0");
                root.setPname(name);
                root.setCourseid(teachplan.getCourseid());
                root.setGrade("1");
                root.setStatus("0");
                //保存根节点
                teachplanRepository.save(root);
            }else {
                root = teachplanList.get(0);
                // teachplan.setParentid(root.getId());
//                teachplan.setGrade("2");
//                teachplanRepository.save(teachplan);
            }
            teachplan.setParentid(root.getId());
            teachplan.setGrade("2");
            teachplan.setStatus("0");
            teachplanRepository.save(teachplan);
        }else {
            teachplanRepository.save(teachplan);
        }
     return new ResponseResult(CommonCode.SUCCESS);
    }
}
